#include "CNet.h"

// 一直回响处理客户端发来的信息 
Result HandleClientCallBack(void* selfConnection,char* content,int size) {
    Connection* connection = (Connection*)selfConnection;

    // 打印接收到的消息
    char temp[512];
    if (size >= sizeof(temp)) {
        size = sizeof(temp) - 1; // 限制 size 以防止溢出
    }
    memcpy(temp, content, size);
    temp[size] = '\0'; 
    printf("%d 收到来自客户端的消息: %.*s\n", connection->connectId, size, temp);
    
    // 如果前四个字母是exit，则退出
    char buffer[5];  // 4 字符 + 1 个 \0
    if (size < 4) {
        memset(buffer, 0, sizeof(buffer));  // 如果 content 长度不足，清空 buffer
        memcpy(buffer, content, size);      // 复制实际接收到的数据
    } else {
        strncpy(buffer, content, 4);
    }
    buffer[4] = '\0';  // 确保 buffer 是一个有效的 C 字符串
    if (strcmp(buffer, "exit") == 0) {
        printf("%d 客户端退出\n", connection->connectId);
        connection->isClosed = 1;
        return NewResult("客户端退出");
    }
    
    if(write(connection->TCPConnect_fd, content, size) < 0) {
        perror("write error");
        connection->isClosed=1;
        return  NewResult("写入数据发生错误") ;
    }
    return NewSuccess();
}

// 一直回响处理客户端发来的信息 
Result HandleRequestCallBack(void* selfRequest) {
    Request* request = (Request*)selfRequest;
    Connection* connection = (Connection*)request->connection;

    // 打印接收到的消息
    char temp[512];
    if (request->data->size >= sizeof(temp)) {
        request->data->size = sizeof(temp) - 1; // 限制 size 以防止溢出
    }
    memcpy(temp, request->data->content, request->data->size);
    temp[request->data->size] = '\0'; 
    printf("%d 收到来自客户端的消息: %.*s\n", connection->connectId, request->data->size, temp);
    
    // 如果前四个字母是exit，则退出
    char buffer[5];  // 4 字符 + 1 个 \0
    if (request->data->size < 4) {
        memset(buffer, 0, sizeof(buffer));  // 如果 content 长度不足，清空 buffer
        memcpy(buffer, request->data->content, request->data->size);      // 复制实际接收到的数据
    } else {
        strncpy(buffer, request->data->content, 4);
    }
    buffer[4] = '\0';  // 确保 buffer 是一个有效的 C 字符串
    if (strcmp(buffer, "exit") == 0) {
        printf("%d 客户端退出\n", connection->connectId);
        connection->isClosed = 1;
        return NewResult("客户端退出");
    }
    
    if(write(connection->TCPConnect_fd, request->data->content, request->data->size) < 0) {
        perror("write error");
        connection->isClosed=1;
        return  NewResult("写入数据发生错误") ;
    }
    return NewSuccess();
}